/**
 * Created by Freeman on 2018/1/20.
 */

import {
  RENAME_TITLE, DIS_LIKE_TOPIC, TOPIC_PRAISES_TOGGLE,
  TOPIC_FAVORITE_TOGGLE
} from '../../../constants/ActionTypes'

function topicReducer (topic, action) {
  switch (action.type) {
    case RENAME_TITLE:
      return {...topic, topicType: action.title}
    case DIS_LIKE_TOPIC:
      return {...topic, dislike: true}
    case TOPIC_PRAISES_TOGGLE : {
      return {
        ...topic,
        liked: topic.liked === 1 ? 0 : 1,
        thumbsUp: topic.liked === 1 ? topic.thumbsUp - 1 : topic.thumbsUp +1,
      }
    }
    case TOPIC_FAVORITE_TOGGLE : {
      return {
        ...topic,
        favorite: topic.favorite === 1 ? 0 : 1,
      }
    }
    default:
      return topic
  }
}

export default function reducer (state = {}, action) {
  switch (action.type) {
    case DIS_LIKE_TOPIC :
    case TOPIC_PRAISES_TOGGLE:
    case TOPIC_FAVORITE_TOGGLE:
    case RENAME_TITLE: {
      const topic = state[action.id]
      if (topic) {
        return {
          ...state,
          [action.id]: topicReducer(topic, action),
        }
      }
      return state
    }
    default:
      return state
  }
}
